Uec3.AddPickInventoryWindow = Ext.extend(Ext.UecWindow,{
	editCount : 0,
	
	constructor : function(config){
		
		this.params = config.params||{};
		
		this.source_combo = Uec3.App.dictionary.getCombo("part_source",{hiddenName:'source',fieldLabel:'来源',allowBlank:false,editable:true,showWhole:true});
		
		this.partPropertyCodeCombo = Uec3.App.fieldFactory.getPartPropertyCodeCombo({fieldLabel:'零件编码'});		
	 	
	 	this.northPanel = new Ext.form.FormPanel({
			frame:true,
			border:false,
			height:100,
			region:'north',
			items:[
			   {
			     layout:'column',			    
			     items:[
			       {
			         columnWidth:0.3,
			         layout:'form',
			         labelWidth:53,			        
			         defaults:{anchor:'100%'},
			         items:[			           
			           this.partPropertyCodeCombo,
			           {xtype:'textfield',fieldLabel:'名称',name:'name',readOnly:true,style:{background:'#dddddd'}},
			           {xtype:'numberfield',fieldLabel:'出库数量',name:'quantity',readOnly:true,style:{background:'#dddddd'}}
			         ]
			       },{
			       	 columnWidth:0.3,
			         layout:'form',
			         labelWidth:53,
			         defaults:{anchor:'99%', labelStyle:"padding-left:5px"},
			         items:[
			           this.source_combo,
			           {xtype:'textfield',fieldLabel:'品牌',name:'brand'},
			           {xtype:'numberfield',fieldLabel:'已拣数量',name:'pickedQuantity',readOnly:true,style:{background:'#dddddd'}}
			         ]
			       },{
			       	columnWidth:0.3,
			       	layout:'form',
			       	labelWidth:53,
			       	defaults:{labelStyle:"padding-left:5px"},
			       	items:[	
			       	   {xtype:'button',text:'查找',width:100,style:{marginLeft:'61px',marginBottom:'3px'},scope:this,handler:this.searchInventory},
			       	   {xtype:'textfield',fieldLabel:'车型',name:'carModel',anchor:'90%',style:{textLeft:'3px'}}			       	  			       	   
			       	]
			       }
			     ]
			   }
			]
		});
		
		this.inventory_grid_store = new Ext.data.JsonStore({			
			url:Uec3.App.Constants.homeUrl+'/inventory/pickInventoryToSale.do',
			root:'items',
			totalProperty:'total',
			fields:['partId',{name:'inventoryIdBySeller',mapping:'id'},'isSelected','code','source','sourceName','name','onHand','measurementUnit','quantity','orderQuantity','documentCode','brand','carModel',{name:'price',mapping:'retailPrice'},'origin','storeId','storePyCode','storeName','shelf','differentQty','isDone']
		});
		
		var inventory_grid_actionCol =  {
			header:'操作',
			xtype:'anchorcolumn',
			width : 100,
			dataIndex : 'act',
			items:[
				{text:"选中 ",scope:this,handler:this.addToInventoryGrid,getVisiblity : this.showAddLink},
				{text:"修改 ",scope:this,handler:this.modifyToInventoryGrid,getVisiblity : this.showModifyLink},
				{text:"取消",scope:this,handler:this.deleteSaleItem,getVisiblity : this.showCancelLink}
			]
		};
		
		var inventory_grid_colName = new Ext.grid.ColumnModel({
			columns:[new Ext.grid.RowNumberer(),inventory_grid_actionCol,
			    {header:'已拣数量',dataIndex:'quantity',editor : new Ext.form.NumberField({ allowBlank: false,allowNegative: false})},
			    {header:'是否已拣',dataIndex:'isSelected',css:'background-color:#dddddd;'},			    
			    {header:'库存数量',dataIndex:'onHand',css:'background-color:#dddddd;'},
			    {header:'批次',dataIndex:'documentCode',css:'background-color:#dddddd;'},
	       		{header:'零件编码',dataIndex:'code',css:'background-color:#dddddd;',width:150},
	       		{header:'零件名称',dataIndex:'name',css:'background-color:#dddddd;',width:130},
	       		{header:'来源',dataIndex:'sourceName',css:'background-color:#dddddd;'},
	       		{header:'单位',dataIndex:'measurementUnit',css:'background-color:#dddddd;'},
	       		{header:'品牌',dataIndex:'brand',css:'background-color:#dddddd;'},
	       		{header:'车型',dataIndex:'carModel',css:'background-color:#dddddd;'},	       		   		
	       		{header:'销售价',dataIndex:'price',css:'background-color:#dddddd;'},	       		
	       		{header:'产地',dataIndex:'origin',css:'background-color:#dddddd;'},
	       		{header:'仓库',dataIndex:'storeName',css:'background-color:#dddddd;'},
	       		{header:'仓位',dataIndex:'shelf',css:'background-color:#dddddd;'}
	   		],
	    	defaults: {
          		//sortable: true,
          		menuDisabled: true,
          		width:120
       		}
		});
		var module =this;
		this.centerPanel = new Ext.grid.EditorGridPanel({
			  height:280,
	   	      viewConfig:{
	   	         scrollOffset:20
	   	      },	   	      
	   	      autoScroll : true,
	   	      titleCollapse:true,
	   	      region:'center',
	   	      clicksToEdit:1,
	          colModel:inventory_grid_colName,
	          selModel:new Ext.grid.RowSelectionModel({moveEditorOnEnter:true,singleSelect :true}),
	          store:this.inventory_grid_store,	           
	          columnLines :true,
	          bbar:new Ext.PagingToolbar({		        	
		            pageSize:20,
	                store:this.inventory_grid_store,
	                displayInfo: true,
	                displayMsg: '第 {0} - {1} 条  共 {2} 条',
                    emptyMsg: "没有记录 ",                    
                    listeners:{                   
                    }
		     }),
		     listeners:{
		     		 'beforeedit':function(e){
		     		 	e.record.set('isDone',false);
		     		 },
                     'afteredit':function(e){
                     	 if(e.field == 'quantity'){                   	 	
                     	 	if(e.value == 0){
                     	 		Ext.MessageBox.alert("提示","请输入正确的数量!")
                     	 	}
                     	    if(e.record.data.onHand < e.value){
                     	    	Ext.MessageBox.alert("提示","出库数量不能大于库存数量!");
                     	    	e.record.set('quantity',e.originalValue);
                     	    }else{
                     	    	var differentQty;
                     	    	if(e.record.isDone){
                     	    		differentQty = e.value - e.originalValue;                    	    		 
                     	    	}else{
                     	    		differentQty = parseInt(e.value - e.originalValue) + (Ext.isEmpty(e.record.get('differentQty'))?0:parseInt(e.record.get('differentQty')));
                     	    	}
                     	    	e.record.set('differentQty',differentQty);   
                     	    }
                     	  	e.grid.getView().refresh(); 
                     	 }
                     },
                     'mouseout':function(e){
						if(module.centerPanel.activeEditor){
							module.editCount++;
							if(module.editCount==2){
								module.editCount=0;
								module.centerPanel.stopEditing();
							}
						}
					}
                }
		});
		
		config = Ext.apply(config||{},{items:[this.northPanel,this.centerPanel]});
		
		Uec3.AddPickInventoryWindow.superclass.constructor.call(this,config);
	},
	
	 //private
	initComponent:function(){
		Uec3.AddPickInventoryWindow.superclass.initComponent.call(this);
	},
	
	//private 
	initEvents : function(){
		Uec3.AddPickInventoryWindow.superclass.initEvents.call(this);
		this.on('show',this.winAfterShow,this);
		this.source_combo.on('select',this.autoFillDetailForm,this);
		this.partPropertyCodeCombo.on('select',this.selectCode,this);
		this.partPropertyCodeCombo.on('change',this.selectCode,this);
		this.inventory_grid_store.on('load',this.renderIsSeletecd,this);
	},
	
	showAddLink : function(value,meta,record,rowIndex,colIndex,store){
		if(record.get('isSelected') == ''||Ext.isEmpty(record.get('isSelected'))){
			return true;
		}
		return false;
	},
	
	showModifyLink : function(value,meta,record,rowIndex,colIndex,store){
		if(record.get('isSelected') == '是'){
			return true;
		}
		return false;
	},
	
	showCancelLink : function(value,meta,record,rowIndex,colIndex,store){
		if(record.get('isSelected') == '是'){
			return true;
		}
		return false;
	},
	
	addInventoryItem : function(rowIndex){
		var record = this.inventory_grid_store.getAt(rowIndex);
		if(Ext.isEmpty(record.get('quantity'))|| record.get('quantity') == 0){
			Ext.Msg.alert("提示","请选择正确的出库数量!");
		}else{
			var searchForm = this.northPanel.getForm();
			record.set('orderQuantity',searchForm.findField('quantity').getValue());
			var isSuccess = this.params.callback.call(this.params.scope,record,this.hasOrder,record.get('differentQty'));
			if(isSuccess){				
				var pQtyField = searchForm.findField('pickedQuantity');
				var pfQty = Ext.isEmpty(pQtyField.getValue())?0:parseInt(pQtyField.getValue());
				var dQty = Ext.isEmpty(record.get('differentQty'))?0:parseInt(record.get('differentQty'));
				var pQty = pfQty + dQty;
				pQtyField.setValue(pQty);
				record.set('isSelected',"是");
			}else{	
				var qty = record.get('quantity')-(Ext.isEmpty(record.get('differentQty'))?0:parseInt(record.get('differentQty')));
				record.set('quantity',qty);
				parseInt(qty) == 0 ? record.set('isSelected'," "):record.set('isSelected',"是");			
			}
			record.set('isDone',true);
			record.set('differentQty',0);
			this.centerPanel.getView().refresh();
		}
	},
	
	addToInventoryGrid : function(grid, rowIndex, colIndex, item, e){
		this.addInventoryItem(rowIndex);
	},
	
	modifyToInventoryGrid : function(grid, rowIndex, colIndex, item, e){
		this.addInventoryItem(rowIndex);
	},
	
	deleteSaleItem : function(grid, rowIndex, colIndex, item, e){
		var record = grid.getStore().getAt(rowIndex);		
		var invIndex = this.params.scope.inventorySale_grid_store.findExact('inventoryIdBySeller',parseInt(record.get('inventoryIdBySeller')));
		this.params.scope.centerPanel.setActiveTab(1);
		this.params.scope.inventorySale_grid.getSelectionModel().selectRow(invIndex);		
	    this.params.scope.delItemHandler(true);	
	
		var searchForm = this.northPanel.getForm();
		var pQtyField = searchForm.findField('pickedQuantity');
		var pfQty = Ext.isEmpty(pQtyField.getValue())?0:parseInt(pQtyField.getValue());
		var dQty = Ext.isEmpty(record.get('quantity'))?0:parseInt(record.get('quantity'));
		var pQty;
		if(record.get('isDone')){
			pQty = pfQty - dQty;		
		}else{
			var dfQty = Ext.isEmpty(record.get('differentQty'))?0:parseInt(record.get('differentQty'));
			pQty = pfQty - (dQty - dfQty);
		}
		pQtyField.setValue(pQty);	
		record.set('quantity','');
		record.set('isSelected','');
		record.set('differentQty',0);
		record.set('isDone',true);
		grid.getView().refresh();
				
	},
	
	renderIsSeletecd : function(store,records,options){		
		var inventRecords = this.params.inventoryStore.getRange();
		Ext.each(inventRecords,function(record,index,inventRecords){
			var index = store.findExact('inventoryIdBySeller',parseInt(record.get('inventoryIdBySeller')));
			if(index != -1){
				var iRecord = store.getAt(index);
				iRecord.set('quantity',record.get('quantity'));
				iRecord.set('isSelected',record.get('quantity') > 0 ? "是" : " ");
			}
		},this);
	},

	
	selectCode  :function(){
		var value = this.partPropertyCodeCombo.getValue();
		this.northPanel.getForm().el.dom.reset();
		this.inventory_grid_store.removeAll();
		this.partPropertyCodeCombo.setValue(value);
	},
	
	autoFillDetailForm:function(){
		var source = this.source_combo.getValue();
		if(!Ext.isEmpty(source)){
			var code = this.northPanel.getForm().findField("code").getValue();
			this.inventory_grid_store.removeAll();
			if(code){
				Ext.Ajax.request({
					url :Uec3.App.Constants.homeUrl+"/part/queryPart!getPartByCodeAndSource.do",
					params :{queryParam:Ext.encode({code:code,source:source})},
					method :"post",
					callback :function(options,success,response){
					     
					},
					success:function(response,options){	                	 
						var resp = Ext.decode(response.responseText);
						if(resp.success){
							if(resp){
								this.northPanel.getForm().setValues(resp);	                	     	          	     	
							}else{
								Ext.MessageBox.alert("提示","此零件编码和来源无相关零件信息,请重试");
								this.northPanel.getForm().findField("source").clearValue();
								this.northPanel.getForm().findField("name").reset();	                	     	
							}	
						}else{
							Ext.MessageBox.alert("提示",resp.msg);
						}	  				       
					},
					failure:function(response,options){
						Ext.MessageBox.alert("提示","数据加载异常");
					}
				});	    		    	 
			}else{
				Ext.MessageBox.alert("提示","请填写零件编码");
			}	    	  	 
		}else{
			this.northPanel.getForm().findField("name").reset();
			this.northPanel.getForm().findField("brand").reset();
			this.northPanel.getForm().findField("carModel").reset();
		}
	},
	
	searchInventory:function(){
		var queryParams = this.northPanel.getForm().getValues();
		delete queryParams.quantity;
		delete queryParams.pickedQuantity;
		this.doRequest(queryParams);		    
	},
	
	doRequest : function(queryParam){
		var myMask = new Ext.LoadMask(this.el,{msg : "正在加载零件库存信息,请稍后....."});
	    myMask.show();
	    this.inventory_grid_store.baseParams = {start:0,limit:20,queryParam:Ext.encode(queryParam)};		   
	    this.inventory_grid_store.load({
	    	callback:function(records,options,success){
	    		myMask.hide();
	    		if(success){
	    	    	var total=records.length;
                   	if(!total){
                    	Ext.MessageBox.alert("提示","未找到相关库存记录");	                    	
                 	}
	    		}else{
	    			Ext.MessageBox.alert("提示",this.reader.jsonData.msg);
	    		}		    		
	    	}
	    });	  
	},
	
	winAfterShow : function(){
		var record = this.params.record;	
		if(Ext.isEmpty(record)){
			this.hasOrder = false;//无引用订单,添加库存件			
		}else{
			this.hasOrder = true;//有引用订单,添加库存件
			this.northPanel.getForm().setValues(record.data);
		    this.searchInventory();
		}
	}
});


Uec3.PickInventoryModule = Ext.extend(Ext.app.Module,{
	
	id:'pickInventory',	
	
	createWindow:function(params){	
		var desktop = this.app.getDesktop();    						
        var win = desktop.getWindow('pickInventoryWindow');
        if (!win) {
			win = desktop.createWindowNoTask({
				    id : "pickInventoryWindow",
				    title : '零件库存选择',
				    width : 1000,
				    height : 400,
				    params:params,
					iconCls : 'acc-icon',
				    maximizable : false,
				    resizable:false,
					maximized:false,
					minimizable:false,
					constrainHeader:true,
					modal:true,
					plain:true,
					taskbuttonTooltip : "零件库存选择",
					layout : "border"
			},Uec3.AddPickInventoryWindow);			
		}else{
			win.params = params;
		}	
		win.show();
	}
});